#pragma semicolon 1
#include <sourcemod>
#include <cstrike>
#include <sdkhooks>
#include <sdktools>
#include <ncs_rpg>

#define VERSION		"Beta 1.0.0"

new ThisSkillID;
new SkillAmount, SkillWeapon;

public Plugin:myinfo =
{
	name		= "[NCS RPG] Skill Stealth",
	author		= "[RUS] DiviX",
	description	= "Skill Stealth for NCS RPG",
	version		= VERSION,
	url			= "N/A"
};

public OnPluginStart()
{
	HookEvent("player_spawn", Event_PlayerSpawn);
}

public RPG_OnSkillsRegister()
{
	ThisSkillID = RegisterSkill("stealth", 5, 15, 10);
	SkillAmount = GetConfigValue("stealth", "amount", 34);
	SkillWeapon = GetConfigValue("stealth", "weapon", 2);
}

public Action:RPG_OnSkillUP(&client, &skillid, &old_value, &new_value)
{
	if(skillid != ThisSkillID)
		return;
	
	SetColor(client, -1, -1, -1, GetAlpha(client)-(SkillAmount*(new_value-old_value)));
	if(SkillWeapon > 0)
	{
		SetAllWeaponAlpha(client, SkillAmount*(new_value-old_value));
		if(new_value > 0)
			OnClientPutInServer(client);
		else
		{
			SDKUnhook(client, SDKHook_PostThinkPost, Hook_PostThinkPost);
			SDKUnhook(client, SDKHook_WeaponEquipPost, Hook_EquipWeaponPost);
			SDKUnhook(client, SDKHook_WeaponDropPost, Hook_WeaponDropPost);
		}
	}
}

public OnClientPutInServer(client)
{
	if(SkillWeapon > 0)
	{
		SDKHook(client, SDKHook_PostThinkPost, Hook_PostThinkPost);
		SDKHook(client, SDKHook_WeaponEquipPost, Hook_EquipWeaponPost);
		SDKHook(client, SDKHook_WeaponDropPost, Hook_WeaponDropPost);
	}
}

public Hook_PostThinkPost(client)
{
	SetEntProp(client, Prop_Send, "m_iAddonBits", 0);
}

public Hook_EquipWeaponPost(client, weapon)
{
	SetAllWeaponAlpha(client, SkillAmount*GetSkillLevel(client, ThisSkillID));
}

public Hook_WeaponDropPost(client, weapon)
{
	if(IsValidEntity(weapon))
	{
		SetEntityRenderMode(weapon, RENDER_NORMAL);
		SetEntityRenderColor(weapon, _, _, _, 255);
	}
}

public Event_PlayerSpawn(Handle:event, const String:name[], bool:dontBroadcast)
{
	new client = GetClientOfUserId(GetEventInt(event, "userid"));
	if(IsValidPlayer(client))
		if(GetClientTeam(client) != CS_TEAM_NONE)
			CreateTimer(0.0, Timer_PostSpawn, client, TIMER_FLAG_NO_MAPCHANGE);
}

public Action:Timer_PostSpawn(Handle:timer, any:client)
{
	if(IsValidPlayer(client, true))
	{
		new level = GetSkillLevel(client, ThisSkillID);
		if(level > 0)
		{
			SetColor(client, -1, -1, -1, GetAlpha(client)-SkillAmount*level);
			if(SkillWeapon > 0)
				SetAllWeaponAlpha(client, SkillAmount*level);
		}
	}
}

SetAllWeaponAlpha(client, alpha)
{
	new weapon = -1;
	for(new i = 0; i < CS_SLOT_GRENADE; i++)
	{
		weapon = GetPlayerWeaponSlot(client, i);
		if(weapon == -1)
			continue;
		
		SetEntityRenderMode(weapon, RENDER_TRANSALPHA);
		SetEntityRenderColor(weapon, _, _, _, GetAlpha(weapon)-alpha);
	}
}